package com.tuo51.manager.controller;


import com.tuo51.evaluate.domain.childrens.Children;
import com.tuo51.core.domain.staffs.Staff;
import com.tuo51.evaluate.repositories.children.ChildrenRepository;
import com.tuo51.evaluate.service.ChildrenService;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.model.MemVerificationCache;
import com.tuo51.foudation.model.StatusResponse;
import com.tuo51.foudation.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Date;

import static com.tuo51.foudation.constant.RequestConstant.TICKET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 测评小程序使用的接口
 */

@RestController
@RequestMapping("/mapi/children")
@Api(value = "/mapi/children", tags = "OP - 宝宝")
public class MAPIChildrenController {

    @Autowired
    private MemVerificationCache cache;

    @Autowired
    private ChildrenService childrenService;

    @Autowired
    private ChildrenRepository childrenRepository;

    @RequestMapping(value = "/list", method = POST)
    public StatusResponse getChildren(@RequestHeader(TICKET) String ticket,
                                      @RequestParam(value = "pageNum", required = false, defaultValue = "0")Integer pageNum,
                                      @RequestParam(value = "pageSize", required = false, defaultValue = "15")Integer pageSize,
                                      @RequestParam(value = "orderBy", required = false)String orderBy,
                                      @RequestParam(value = "searchBy", required = false) String searchBy){
        Staff staff = cache.getStaff(ticket);


        Page<Children> ret = childrenRepository.findAll(new Specification<Children>() {
            @Override
            public Predicate toPredicate(Root<Children> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate base = cb.isFalse(root.get("deleted"));

                if (StringUtils.isNotEmpty(searchBy)){
                    String key = "%" + searchBy + "%";
                    Predicate p = cb.or(cb.like(root.get("name"), key),
                            cb.like(root.get("nickName"), key));
                    base = cb.and(base, p);
                }

                query.where(base);

                if (StringUtils.isNotEmpty(orderBy)){
                    query.orderBy(cb.asc(root.get(orderBy)));
                }else {
                    query.orderBy(cb.desc(root.get("created")));
                }
                return query.getRestriction();
            }
        }, PageRequest.of(pageNum, pageSize));

        return StatusResponse.success(ret);
    }

    @RequestMapping(value = "/detail", method = POST)
    public StatusResponse childrenDetail(@RequestHeader(TICKET) String ticket, String childrenId){
        String staffId = cache.getStaffId(ticket);

        Children c = childrenService.getById(childrenId);
        if(c == null){
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "宝宝不存在");
        }

        c.setMonth(DateUtil.betweenMonths(new Date(), c.getBirthday()));

        return StatusResponse.success(c);
    }

    @RequestMapping(value = "/delete", method = POST)
    public StatusResponse deleteChildren(@RequestHeader(TICKET) String ticket, String childrenId) {
        String staffId = cache.getStaffId(ticket);

        boolean ret = false; //childrenService.deleteChildrenForStaff(childrenId, staffId);

        return StatusResponse.success(ret);
    }

    @ApiOperation("更新宝宝信息，所有字段可选")
    @RequestMapping(value = "/update_child_info", method = POST)
    public StatusResponse updateChildInfo(@RequestHeader(TICKET) String ticket,
                                          String childrenId,
                                          String childrenName,
                                          String nickName,
                                          String avatar,
                                          Integer gender,
                                          String birthday,
                                          String guardianPhone, String guardianName, String guardianRelation,
                                          String weight,
                                          String height,
                                          String header,
                                          String address,
                                          String remark){

        String staffId = cache.getStaffId(ticket);

        if (StringUtils.isEmpty(childrenId)){
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "宝宝不存在");
        }

        Children children = childrenService.getById(childrenId);
        if (children == null){
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "宝宝不存在");
        }

        children = childrenService.edit(children, childrenName, nickName, avatar, guardianPhone,guardianName, guardianRelation,
                birthday, gender, weight, height, header, address, remark);

        return StatusResponse.success(children);

    }
}
